from .utils import *
from django.http import JsonResponse
from rest_framework import status

class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.public_paths = [
            '/api/user/login/',
            '/api/user/register/',
        ]

    def __call__(self, request):
        # 在请求处理之前进行JWT验证
        path = request.path
        if path.startswith('/api/user'):  # 仅对以/api/user开头的请求进行验证
            token = request.META.get('HTTP_AUTHORIZATION')
            if not token:
                return JsonResponse(
                    {'status': status.HTTP_401_UNAUTHORIZED, 
                    'message': '请登录'}, 
                    status=status.HTTP_401_UNAUTHORIZED,
                    json_dumps_params={'ensure_ascii': False}
                    )
            # 验证token
            payload = verify_token(token)
            
            if payload is None:
                return JsonResponse(
                    {'status': status.HTTP_401_UNAUTHORIZED, 
                    'message': '无效的token'}, 
                    status=status.HTTP_401_UNAUTHORIZED
                )
            elif isinstance(payload, dict) and payload.get('expired'):
                return JsonResponse(
                    {'status': status.HTTP_401_UNAUTHORIZED, 
                    'message': 'token已过期，请刷新',
                    'id': payload.get('id')},
                    status=status.HTTP_401_UNAUTHORIZED,
                    json_dumps_params={'ensure_ascii': False}
                )
            
            # 将用户信息添加到请求对象中
            request.user_id = payload.get('id')
                
        return self.get_response(request)